package com.wangjiang.mario.admin.common.util;

import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.stream.Collectors;

public final class ClassPathResourceReader {
    /**
     * path:文件路径
     *
     * @since JDK 1.8
     */
    private final String path;

    /**
     * content:文件内容
     *
     * @since JDK 1.6
     */
    private String content;

    public ClassPathResourceReader(String path) {
        this.path = path;
    }

    /**
     * 获取文本类文件
     *
     * @return
     */
    public String getContent() {
        if (content == null) {
            try {
                ClassPathResource resource = new ClassPathResource(path);
                BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                content = reader.lines().collect(Collectors.joining("\n"));
                reader.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        return content;
    }

    /**
     * 非文本文件
     */
    public BufferedInputStream getInpustream() {
        try {
            ClassPathResource resource = new ClassPathResource(path);
            return (BufferedInputStream) resource.getInputStream();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
